package ink.lovejinhu.swardToOffer;

import ink.lovejinhu.common.TreeNode;

/**
 * @Author: jin
 * @Date: 2021/8/25 20:54
 * @Version: V1.0
 * @Slogan: Great people are not born great, but show their greatness in the process of growing up
 **/
public class Offer_055_II {

    class Res {
        public boolean balance;
        public int height;

        public Res(boolean balance, int height) {
            this.balance = balance;
            this.height = height;
        }
    }

    public boolean isBalanced(TreeNode root) {
        Res dfs = this.dfs(root);
        return dfs.balance;

    }

    public Res dfs(TreeNode root) {
        if (root == null) {
            return new Res(true, 0);
        }
        Res dfsLeft = dfs(root.left);
        Res dfsRight = dfs(root.right);
        if (!dfsLeft.balance) {
            return new Res(false, 0);
        }
        if (!dfsRight.balance) {
            return new Res(false, 0);
        }
        if (Math.abs(dfsLeft.height - dfsRight.height) > 1) {
            return new Res(false, 0);
        }
        return new Res(true, Math.max(dfsLeft.height, dfsRight.height) + 1);

    }


}
